package com.example.nfcschool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.StringReader;
import java.lang.reflect.Method;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import com.example.nfcschool.TListActivity.InsertRecordJsp;

import android.R.integer;
import android.app.ActionBar;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

	SDBHelper db = null;
	long time = 0;

	TextView change_text;
	TextView login_text;
	TextView join_text;
	EditText pw_et;
	CheckBox auto;
	SmemberVO premem;

	String telno = "";
	String telCheck = "";
	String snoCheck = "";
	String sno = "";
	String grade = "";
	boolean cheeting = true;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		FileOutputStream fos = null;
		
		fos = null;
		try {
			// 첫 매개변수는 파일명, 두번째 매개변수는 모드
			fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

			String check1 = "false";
			fos.write(check1.getBytes());
			fos.close();

		} catch (Exception ex) {
			Log.e("파일 save 에러", ex.toString());
		}

		ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
		try {
			
			Class localClass = connectivityManager.getClass();
			Class[] arrayOfClass = new Class[1];
			arrayOfClass[0] = Boolean.TYPE;
			Method localMethod = localClass.getMethod("setMobileDataEnabled",
					arrayOfClass);
			ConnectivityManager localConnectivityManager = connectivityManager;
			Object[] arrayOfObject = new Object[1];
			arrayOfObject[0] = Boolean.valueOf(true);
			localMethod.invoke(localConnectivityManager, arrayOfObject);
			WifiManager wifiManager = (WifiManager) getApplicationContext()
					.getSystemService(Context.WIFI_SERVICE);
			wifiManager.setWifiEnabled(true);

		} catch (Exception e) {
			e.printStackTrace();
		}

		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// ActionBar제거한다.
		ActionBar actionBar = getActionBar();
		actionBar.hide();

		imei(); // 폰 번호

		// 자동로그인
		Intent intent = null;
		if (load().equals("")) {
		} else {
			String[] str = load().split("/");

			if (!(str[0].equals("0"))) {
				new SelectOneJsp().execute();
				finish();

				if (str[1].equals("true"))
					intent = new Intent(this, TListActivity.class)
							.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				else
					intent = new Intent(this, SViewActivity.class)
							.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

				intent.putExtra("tel", telno);
				intent.putExtra("grade", grade);
				startActivity(intent);
				// Toast.makeText(this, "자동로그인 성공", Toast.LENGTH_SHORT).show();

			}
		}
		change_text = (TextView) findViewById(R.id.change_textbtn);
		login_text = (TextView) findViewById(R.id.login_textbtn);
		join_text = (TextView) findViewById(R.id.join_textbtn);
		pw_et = (EditText) findViewById(R.id.pw_edit);
		auto = (CheckBox) findViewById(R.id.auto_login_check);

		login_text.setOnClickListener(this);
		join_text.setOnClickListener(this);
		change_text.setOnClickListener(this);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		new DuplicateJsp().execute();
		super.onResume();

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return super.onOptionsItemSelected(item);
	}

	// 휴대폰 번호를 구하는 메소드.
	public void imei() {
		TelephonyManager tele = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
		telno = tele.getLine1Number();
		if (telno.contains("+82")) {
			telno = "0" + telno.substring(3);
		}

		Log.e("imei()", telno);
	}

	@Override
	public void onClick(View v) {
		int id = v.getId();

		new DuplicateJsp().execute();
		switch (id) {
		case R.id.login_textbtn:

			if (!pw_et.getText().toString().equals("")) { // PW 창 빈 값 err
				EditText pw_et = (EditText) findViewById(R.id.pw_edit);
				int pw = Integer.parseInt(pw_et.getText().toString());
				Intent intent;

				// Login 로직
				if (premem != null) {
					if (pw == premem.getPw()) {
						if (auto.isChecked()) { // 자동 로그인 체크되어있으면 저장소에 암호 저장.
							save(pw, premem.getTeach());
						}
						finish();
						Toast.makeText(this, "로그인 완료", Toast.LENGTH_SHORT)
								.show(); cheeting = false;

						if (premem.getTeach().equals("true")) // 선생님, 학생 판별 후 다른
																// Activity 호출
							intent = new Intent(this, TListActivity.class)
									.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
						else
							intent = new Intent(this, SViewActivity.class)
									.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

						intent.putExtra("tel", telno);
						startActivity(intent);
					} else {
						Toast.makeText(this, "암호를 확인해주세요.", Toast.LENGTH_SHORT)
								.show();
					}
				} else {
					Toast.makeText(this, "등록되지 않은 학생입니다. 먼저 가입을 해주세요.",
							Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(this, "비밀번호를 입력해주세요", Toast.LENGTH_SHORT).show();
			}
			break;

		case R.id.join_textbtn: // 회원가입 버튼
			if (telCheck.equals("true")) {
				Toast.makeText(this, "이미 등록하셨습니다.", Toast.LENGTH_SHORT).show();
			} else {
				Intent intent2 = new Intent(this, JoinActivity.class)
						.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
				startActivity(intent2);
				cheeting = false;
			}
			break;
		case R.id.change_textbtn: // 전화번호 변경 버튼
			Intent intent3 = new Intent(this, TelChangeActivity.class);
			intent3.putExtra("tel", telno);
			startActivity(intent3);
			break;
		}

	}

	public String load() { // 자동 로그인. (저장된 암호값 가지고 오기)
		String pass = "";

		FileInputStream fis = null;
		try {
			if (openFileInput("auto") != null) {

				fis = openFileInput("auto");
				byte[] data2 = new byte[fis.available()];
				fis.read(data2);

				pass = new String(data2);
				fis.close();
			}
		} catch (Exception ex) {
			Log.e("파일 load 에러", ex.toString());
		}
		return pass;
	}

	public void save(int pw, String teach) { // 자동 로그인. (암호값 저장하기.)
		FileOutputStream fos = null;
		try {
			// 첫 매개변수는 파일명, 두번째 매개변수는 모드
			fos = openFileOutput("auto", Activity.MODE_PRIVATE);

			String data = pw + "/" + teach;
			fos.write(data.getBytes());
			fos.close();
			// Toast.makeText(this, "파일이 저장되었습니다.", Toast.LENGTH_SHORT).show();
		} catch (Exception ex) {
			Log.e("파일 save 에러", ex.toString());
		}
	}

	// Font_Login
	@Override
	protected void onStart() {
		Typeface typeFace = Typeface.createFromAsset(getAssets(), "white.ttf");

		TextView tv1 = (TextView) findViewById(R.id.textView1);
		TextView tv2 = (TextView) findViewById(R.id.textView2);
		change_text = (TextView) findViewById(R.id.change_textbtn);
		login_text = (TextView) findViewById(R.id.login_textbtn);
		join_text = (TextView) findViewById(R.id.join_textbtn);

		auto = (CheckBox) findViewById(R.id.auto_login_check);

		tv1.setTypeface(typeFace);
		tv2.setTypeface(typeFace);
		change_text.setTypeface(typeFace);
		login_text.setTypeface(typeFace);
		join_text.setTypeface(typeFace);

		auto.setTypeface(typeFace);

		super.onStart();
	}

	// ㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡㅡWEB DB
	public class SelectOneJsp extends AsyncTask<Void, String, Void> {

		String tag = "";
		StringBuilder sb = new StringBuilder();

		@Override
		protected Void doInBackground(Void... param) {

			try {

				Log.e("pre", "pre");
				try {
					HttpClient client = new DefaultHttpClient();
					String postURL = "http://192.168.0.7:8888/AndroidCheck/SelectOne.jsp";
					HttpPost post = new HttpPost(postURL);

					ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

					params.add(new BasicNameValuePair("tel", telno));

					UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
							HTTP.UTF_8);
					post.setEntity(ent);
					HttpResponse responsePOST = client.execute(post);
					HttpEntity resEntity = responsePOST.getEntity();

					if (resEntity != null) {
						// Log.i("RESPONSE", EntityUtils.toString(resEntity));
						sb.append(EntityUtils.toString(resEntity));
					}
					client.getConnectionManager().shutdown(); // 추가된 코드.
				} catch (Exception ex) {
					Log.i("preeeee", ex.toString());
					Log.i("tel", sb.toString());
				}

				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(sb.toString()));
				int eventType = xpp.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {// 현재 이벤트 타입이
																	// END_DOCUMENT를
																	// 만날때 까지
																	// 반복.

					switch (eventType) {
					case XmlPullParser.START_TAG: // 이벤트 타입에 START_TAG 라면.
						tag = xpp.getName(); // 태그 이름을 추출함.
						if (tag.equals("smember")) {
							premem = new SmemberVO();
						} else if (tag.equals("irum")) {
							premem.setIrum(xpp.nextText());
						} else if (tag.equals("tel")) {
							premem.setTel(xpp.nextText());
						} else if (tag.equals("picture")) {
							premem.setPicture(xpp.nextText());
						} else if (tag.equals("grade")) {
							premem.setGrade(xpp.nextText());
						} else if (tag.equals("pw")) {
							premem.setPw(1111);
						} else if (tag.equals("birth")) {
							premem.setBirth(xpp.nextText());
						} else if (tag.equals("teach")) {
							premem.setTeach(xpp.nextText());
						} else if (tag.equals("adds")) {
							premem.setAdds(xpp.nextText());
						} else if (tag.equals("sno")) {
							sno = xpp.nextText();
							premem.setSno(sno);
						}

						break;

					}
					eventType = xpp.next();
				}

			} catch (Exception e) {
				Log.e("SView Async Err", e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			Log.e("mainEnd?", "send?");

			super.onPostExecute(result);
		}
	}

	public class DuplicateJsp extends AsyncTask<Void, String, Void> {

		String tag = "";
		StringBuilder sb = new StringBuilder();

		@Override
		protected Void doInBackground(Void... param) {

			try {
				Log.e("duplicatejsp()", "send?");
				HttpClient client = new DefaultHttpClient();
				String postURL = "http://192.168.0.7:8888/AndroidCheck/DuplicateCheck.jsp";
				HttpPost post = new HttpPost(postURL);

				ArrayList<NameValuePair> params = new ArrayList<NameValuePair>();

				params.add(new BasicNameValuePair("tel", telno));
				params.add(new BasicNameValuePair("sno", sno));

				UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,
						HTTP.UTF_8);
				post.setEntity(ent);
				HttpResponse responsePOST = client.execute(post);
				HttpEntity resEntity = responsePOST.getEntity();

				if (resEntity != null) {
					sb.append(EntityUtils.toString(resEntity));
				}
				client.getConnectionManager().shutdown(); // 추가된 코드.

				// 데이터 받기
				XmlPullParserFactory factory = XmlPullParserFactory
						.newInstance();
				factory.setNamespaceAware(true);
				XmlPullParser xpp = factory.newPullParser();
				xpp.setInput(new StringReader(sb.toString()));
				int eventType = xpp.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {// 현재 이벤트 타입이
																	// END_DOCUMENT를
																	// 만날때 까지
																	// 반복.

					switch (eventType) {
					case XmlPullParser.START_TAG: // 이벤트 타입에 START_TAG 라면.
						tag = xpp.getName(); // 태그 이름을 추출함.
						if (tag.equals("tel")) {
							telCheck = xpp.nextText();
						} else if (tag.equals("sno")) {
							snoCheck = xpp.nextText();
						}
						break;

					}
					eventType = xpp.next();
				}

			} catch (Exception e) {
				Log.e("MainDuplicateCheck Async Err", e.toString());
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {

			Log.e("mainDuplicateEnd?", "send?");

			if (telCheck.equals("true"))
				new SelectOneJsp().execute();

			super.onPostExecute(result);
		}

	}

	@Override
	public void onBackPressed() {
		if (System.currentTimeMillis() >= time + 2000) {
			Toast.makeText(this, "한 번 더 누르면 종료됩니다.", Toast.LENGTH_SHORT).show();
			time = System.currentTimeMillis();
		} else {
			finishAffinity();
		}
	}

	@Override
	protected void onStop() {
		if (cheeting) {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(getApplicationContext().CONNECTIVITY_SERVICE);
			try {
				Toast.makeText(getApplicationContext(), "Into try/catch",
						Toast.LENGTH_LONG).show();
				Class localClass = connectivityManager.getClass();
				Class[] arrayOfClass = new Class[1];
				arrayOfClass[0] = Boolean.TYPE;
				Method localMethod = localClass.getMethod(
						"setMobileDataEnabled", arrayOfClass);
				ConnectivityManager localConnectivityManager = connectivityManager;
				Object[] arrayOfObject = new Object[1];
				arrayOfObject[0] = Boolean.valueOf(false);
				localMethod.invoke(localConnectivityManager, arrayOfObject);
				WifiManager wifiManager = (WifiManager) getApplicationContext()
						.getSystemService(Context.WIFI_SERVICE);
				wifiManager.setWifiEnabled(false);

			} catch (Exception e) {
				e.printStackTrace();
			}
			FileOutputStream fos = null;
			Toast.makeText(getApplicationContext(), "예외처리로 인한 데이터차단!!", 2000).show();
			fos = null;
			try {
				// 첫 매개변수는 파일명, 두번째 매개변수는 모드
				fos = openFileOutput("networkcheck", Activity.MODE_PRIVATE);

				String check1 = "true";
				fos.write(check1.getBytes());
				fos.close();
				Toast.makeText(getApplicationContext(), "파일이 저장되었습니다.",
						Toast.LENGTH_SHORT).show();
			} catch (Exception ex) {
				Log.e("파일 save 에러", ex.toString());
			}
		}
		super.onPause();
	}

}
